package com.ting.encrypt.core;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.ting.encrypt.annotation.EncryptField;
import com.ting.encrypt.encrypt.BaseEncrypt;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.lang.reflect.Field;
import java.sql.Connection;

public class EncryptFieldEntityListener implements Interceptor {

//    @Override
//    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter,
//                            RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
//        // 打印 SQL 语句
//        System.out.println("Executing SQL: " + boundSql.getSql());
//    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        return null;
    }


//    @Override
//    public void afterQuery(Executor executor, MappedStatement ms, Object parameter,
//                           RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql, Object result) {
//        // SQL 执行后的操作
//    }
//
//    @Override
//    public void beforeInsert(T entity) {
//        Field[] fields = entity.getClass().getDeclaredFields();
//        for (Field field : fields) {
//            if (field.isAnnotationPresent(EncryptField.class)) {
//                field.setAccessible(true);
//                try {
//                    EncryptField annotation = field.getAnnotation(EncryptField.class);
//                    Class<? extends BaseEncrypt> aClass = annotation.encryptType();
//                    BaseEncrypt baseEncrypt = aClass.newInstance();
//                    String value = (String) field.get(entity);
//                    field.set(entity, baseEncrypt.encrypt(value));
//                } catch (IllegalAccessException e) {
//                    throw new RuntimeException("Failed to access field", e);
//                }
//            }
//        }
//    }
//
//    @Override
//    public void afterSelect(T entity) {
//        Field[] fields = entity.getClass().getDeclaredFields();
//        for (Field field : fields) {
//            if (field.isAnnotationPresent(EncryptField.class)) {
//                field.setAccessible(true);
//                try {
//                    String value = (String) field.get(entity);
//                    field.set(entity, CryptoUtil.decrypt(value));
//                } catch (IllegalAccessException e) {
//                    throw new RuntimeException("Failed to access field", e);
//                }
//            }
//        }
//    }
}